﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Extensil.Common;
using Vibz.SharePoint;
using Vibz.SharePoint.Entity;
using System.Security.Principal;
using Vibz.TeamAssignment.Common.Entity;

namespace Vibz.TeamAssignment.Sharepoint
{
    public partial class SharePointSettings : Form
    {
        SPWeb _web;
        SPSiteData _siteData;
        SPUser _user;
        BaseCategory _category;
        BackgroundWorker bwConfigure;
        SPList _SPList;
        bool _closeForm = false;
        
        public SharePointSettings(BaseCategory category)
        {
            InitializeComponent();
            _category = category;
            txtSPSite.Text = System.Configuration.ConfigurationManager.AppSettings["SPSite"];

        }
        

        private void btnConfigure_Click(object sender, EventArgs e)
        {
            bwConfigure = new BackgroundWorker();
            bwConfigure.WorkerReportsProgress = true;
            bwConfigure.WorkerSupportsCancellation = true;
            bwConfigure.DoWork += new DoWorkEventHandler(bwConfigure_DoWork);
            bwConfigure.ProgressChanged += new ProgressChangedEventHandler(bwConfigure_ProgressChanged);
            bwConfigure.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(bwConfigure_RunWorkerCompleted);
            lblStatus.Visible = true;
            pbStatus.Visible = true;
            bwConfigure.RunWorkerAsync(new object[] { txtSPSite.Text, rbExisting.Checked });
        }
        void bwConfigure_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbStatus.Value = e.ProgressPercentage;
            lblStatus.Text = e.UserState.ToString();
        }
        void bwConfigure_DoWork(object sender, DoWorkEventArgs e)
        {
            ConfigureSite(((object[])e.Argument).GetValue(0).ToString(), (bool)((object[])e.Argument).GetValue(1));
        }

        void ConfigureSite(string siteUrl, bool isExisting)
        {
            bwConfigure.ReportProgress(5, "Validating site url.");
            if(String.IsNullOrEmpty(siteUrl.Trim()) || !SPSiteData.IsValidSite(siteUrl))
            {
                AlertBox.ShowDialog(new Exception("Please provide a valid url."));
                return;
            }

            bwConfigure.ReportProgress(10, "Checking site contents.");
            _siteData = new SPSiteData(siteUrl);
            string[] lists = _siteData.GetAllList();
            if(isExisting)
            {
                bool missingList = false;
                foreach(string list in new string[] { "Task", "TaskAssignment", "TaskGroup", "TaskGroupOwner", "TeamMember", "TaskMaster" })
                {
                    if(!lists.Contains(list))
                    {
                        missingList = true;
                        break;
                    }
                }
                if(missingList)
                {
                    AlertBox.ShowDialog("Some of the required component is missing from the given site. This site can not be configured with this application. Please contact youe administrator for more help.");
                    return;
                }
                bwConfigure.ReportProgress(50, "Configuring site url.");
                _category.AddUpdaeApplicationSettingParameter("SPSite", siteUrl);
                _closeForm = true;
            }
            else
            {
                _user = new SPUser(siteUrl);
                bwConfigure.ReportProgress(20, "Validating your authentication.");
                if(!_user.IsUserAdmin(WindowsIdentity.GetCurrent().Name))
                {
                    AlertBox.ShowDialog("You must have administrative priviledge on this site to create task assignment components. Please contact youe administrator for more help.");
                    return;
                }

                bool listFound = false;
                foreach(string list in new string[] { "Task", "TaskAssignment", "TaskGroup", "TaskGroupOwner", "TeamMember", "TaskMaster" })
                {
                    if(lists.Contains(list))
                    {
                        listFound = true;
                        break;
                    }
                }
                if(listFound)
                {
                    AlertBox.ShowDialog("The site contradicts with some of the task contents. This site can not be configured with this application. Please contact youe administrator for more help.");
                    return;
                }

                bwConfigure.ReportProgress(30, "Creating lists.");
                if(CreateSPLists(siteUrl))
                {
                    _category.AddUpdaeApplicationSettingParameter("SPSite", siteUrl);
                    _closeForm = true;
                }
            }
        }
        public bool CreateSPLists(string siteUrl)
        {
            try
            {
                _web = new SPWeb(siteUrl);

                // 1. TaskMaster
                bwConfigure.ReportProgress(40, "Creating lists. - TaskMaster");
                _web.CreateList("TaskMaster", "Task Master", new ColumnInfo[]
                    {
                        new ColumnInfo("Key", ColumnType.Text),
                        new ColumnInfo("Value", ColumnType.Text)
                    }.ToList());

                Dictionary<string, object> param = new Dictionary<string, object>();
                param.Add("Key", TaskMasterEntry.WorkingHoursInDay);
                param.Add("Value", 8);
                _web.AddListItem("TaskMaster", param);

                param = new Dictionary<string, object>();
                param.Add("Key", TaskMasterEntry.AutoMail);
                param.Add("Value", true);
                _web.AddListItem("TaskMaster", param);

                param = new Dictionary<string, object>();
                param.Add("Key", TaskMasterEntry.Domain);
                param.Add("Value", "");
                _web.AddListItem("TaskMaster", param);

                // 2. TaskGroup
                bwConfigure.ReportProgress(50, "Creating lists. - TaskGroup");
                _web.CreateList("TaskGroup", "TaskGroup", new ColumnInfo[]
                    {
                    }.ToList());

                // 3. TaskGroupOwner
                bwConfigure.ReportProgress(60, "Creating lists. - TaskGroupOwner");
                _web.CreateList("TaskGroupOwner", "TaskGroupOwner", new ColumnInfo[]
                    {
                        new ColumnInfo("GroupId", ColumnType.Number),
                        new ColumnInfo("OwnerId", ColumnType.Text)
                    }.ToList());

                // 4. Task
                bwConfigure.ReportProgress(70, "Creating lists. - Task");
                _web.CreateList("Task", "Task", new ColumnInfo[]
                    {
                        new ColumnInfo("ParentID", ColumnType.Number),
                        new ColumnInfo("TaskDescription", ColumnType.Note),
                        new ColumnInfo("DueDate", ColumnType.DateTime),
                        new ColumnInfo("EstimatedDuration", ColumnType.Number),
                        new ColumnInfo("ActualDuration", ColumnType.Number),
                        new ColumnInfo("GroupId", ColumnType.Number),
                        new ColumnInfo("TaskStatus", ColumnType.MultiChoice)
                        {
                            AssociatedItems = Enum.GetNames(typeof(TaskStatus))
                        },
                        new ColumnInfo("CreatedBy", ColumnType.Text)
                    }.ToList());

                // 5. TaskAssignment
                bwConfigure.ReportProgress(80, "Creating lists. - TaskAssignment");
                _web.CreateList("TaskAssignment", "TaskAssignment", new ColumnInfo[]
                    {
                        new ColumnInfo("TaskID", ColumnType.Number),
                        new ColumnInfo("AssignedTo", ColumnType.Text),
                        new ColumnInfo("AssignRequestDate", ColumnType.DateTime),
                        new ColumnInfo("AssignComment", ColumnType.Note),
                        new ColumnInfo("AssignBy", ColumnType.Text),
                        new ColumnInfo("IsRequest", ColumnType.Boolean),
                        new ColumnInfo("AssignStatus", ColumnType.MultiChoice)
                        {
                            AssociatedItems = Enum.GetNames(typeof(AssignStatus))
                        }
                    }.ToList());

                // 6. TeamMember
                bwConfigure.ReportProgress(90, "Creating lists. - TeamMember");
                _web.CreateList("TeamMember", "TeamMember", new ColumnInfo[]
                    {
                        new ColumnInfo("ManagerID", ColumnType.Text),
                        new ColumnInfo("MemberID", ColumnType.Text)
                    }.ToList());

                return true;
            }
            catch(Exception exc)
            {
                bwConfigure.ReportProgress(100, "Deleting lists.");
                AlertBox.ShowDialog("Error occured while creating sharepoint list objects. Click OK to rollback.\r\n\tDetails: "
                    + exc.Message, "Error", AlertBoxButtons.OK);
                DeleteAllList();

                return false;
            }
        }
        void DeleteAllList()
        {
            bwConfigure.ReportProgress(90, "Deleting lists. - TaskMaster");
            _web.DeleteListIfExists("TaskMaster");
            bwConfigure.ReportProgress(80, "Deleting lists. - TaskGroup");
            _web.DeleteListIfExists("TaskGroup");
            bwConfigure.ReportProgress(70, "Deleting lists. - TaskGroupOwner");
            _web.DeleteListIfExists("TaskGroupOwner");
            bwConfigure.ReportProgress(60, "Deleting lists. - Task");
            _web.DeleteListIfExists("Task");
            bwConfigure.ReportProgress(50, "Deleting lists. - TaskAssignment");
            _web.DeleteListIfExists("TaskAssignment");
            bwConfigure.ReportProgress(40, "Deleting lists. - TeamMember");
            _web.DeleteListIfExists("TeamMember");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _web = new SPWeb(txtSPSite.Text);
            bwConfigure = new BackgroundWorker();
            bwConfigure.WorkerReportsProgress = true;
            bwConfigure.WorkerSupportsCancellation = true;
            bwConfigure.DoWork +=new DoWorkEventHandler(bwDelete_DoWork);
            bwConfigure.ProgressChanged +=new ProgressChangedEventHandler(bwConfigure_ProgressChanged);
            bwConfigure.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwConfigure_RunWorkerCompleted);
            lblStatus.Visible = true;
            pbStatus.Visible = true;
            bwConfigure.RunWorkerAsync();
        }

        void bwConfigure_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblStatus.Visible = false;
            pbStatus.Visible = false;

            if(_closeForm)
            {
                this.DialogResult = DialogResult.OK;
                this.ParentForm.Close();
            }
        }
        void bwDelete_DoWork(object sender, DoWorkEventArgs e)
        {
            DeleteAllList();
        }
    }
}
